//
//  JiangYuanViewController.m
//  JiuKuGospel
//
//  Created by jiukuyinyue on 16/8/23.
//  Copyright (c) 2016年 JiuKuForApp. All rights reserved.
//

#import "JiangYuanViewController.h"
#import "ShiGeCustomTableViewCell.h"

@interface JiangYuanViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong)UITableView * jiangDaoTab;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, assign)NSInteger pageNum;

@property (nonatomic, strong)NSMutableArray * jiangYuanArr;
@property (nonatomic, strong)JKShareCollectDownView * selectAddView;    //分享下载多功能

//@property (nonatomic, strong)MBProgressHUD *hud;

@end

@implementation JiangYuanViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.playSongView.hidden = NO;
    [appDelegate.window bringSubviewToFront:appDelegate.playSongView];
    [TheHomeManager shareTheHomeManager].nowViewController = self;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    self.navigationController.navigationBar.hidden = NO;
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    //导航栏颜色
    self.navigationController.navigationBar.barTintColor = JK_HUISE_LINE_COLOR;
    //导航栏字体颜色
    self.navigationItem.title = self.titleStr;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
    
    self.pageNum = 1;
    
    UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    UIImageView * LeftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 11, 19)];
    LeftImageView.userInteractionEnabled = YES;
    NSString * backStr = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"new返回%@", [TheHomeManager shareTheHomeManager].iPhone23] ofType:@"png"];
    LeftImageView.image = [UIImage imageWithContentsOfFile:backStr];
    [leftView addSubview:LeftImageView];
    UITapGestureRecognizer * backTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftBtnAction)];
    [leftView addGestureRecognizer:backTap];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];

    [self setupUI];
    [self loadJiangYuanData];
    
}

- (void)setupUI
{
    
    self.jiangDaoTab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-60) style:UITableViewStylePlain];
    _jiangDaoTab.delegate = self;
    _jiangDaoTab.dataSource = self;
    [self.view addSubview:_jiangDaoTab];
    
    
    //cell分割线顶头
    if ([self.jiangDaoTab respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.jiangDaoTab setSeparatorInset: UIEdgeInsetsZero];
    }
    if ([self.jiangDaoTab respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.jiangDaoTab setLayoutMargins: UIEdgeInsetsZero];
    }
    [self setExtraCellLineHidden:_jiangDaoTab];
    
    __block JiangYuanViewController * jiangDVC = self;
    [_jiangDaoTab addHeaderWithCallback:^{
        jiangDVC.pageNum = 1;
        [jiangDVC loadJiangYuanData];
        
    }];
    
    [_jiangDaoTab addFooterWithCallback:^{
        jiangDVC.pageNum++;
        [jiangDVC loadJiangYuanData];

    }];

    
    
    
    UITapGestureRecognizer * randomTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(randomPlaySongs)];
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    [_headerView addGestureRecognizer:randomTap];
    //随机
    UIView * randomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _headerView.height, _headerView.height)];
    [_headerView addSubview:randomView];
    UIImageView * tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake((randomView.width-20)/2, (randomView.height-20)/2, 20, 20)];
    tempImageView.image = [UIImage imageNamed:@"randomStop@3x.png"];
    [randomView addSubview:tempImageView];
    UILabel * tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(randomView.right, 0, self.view.width-100, _headerView.height)];
    tempLabel.text = @"随机播放全部";
    tempLabel.font = FONT_16;
    [_headerView addSubview:tempLabel];
    //多选
    UITapGestureRecognizer * moreSelectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreSelectTap)];
    UIView * moreSelectView = [[UIView alloc] initWithFrame:CGRectMake(self.view.width-60, 0, 60, _headerView.height)];
    [moreSelectView addGestureRecognizer:moreSelectTap];
//    [_headerView addSubview:moreSelectView];
    //46X38  moreSelect@3x.png
    UIImageView * moreSelectImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 12, 20, 16)];
    moreSelectImageV.userInteractionEnabled = YES;
    moreSelectImageV.image = [UIImage imageNamed:@"moreSelect@3x.png"];
    [moreSelectView addSubview:moreSelectImageV];
    UILabel * moreSelectLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 5, 30, 30)];
    moreSelectLabel.text = @"多选";
    moreSelectLabel.font = FONT_14;
    [moreSelectView addSubview:moreSelectLabel];
    
    
    //下划线
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, _headerView.height-0.5, _headerView.width, 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [_headerView addSubview:lineView];
    _jiangDaoTab.tableHeaderView = _headerView;

    
    
    
    //分享下载多功能
    self.selectAddView = [[JKShareCollectDownView alloc] initWithFrame:CGRectMake(self.view.width-180, 50, 170, 28)];
    [_selectAddView.downBtn addTarget:self action:@selector(downClick:) forControlEvents:UIControlEventTouchUpInside];
    [_selectAddView.collectBtn addTarget:self action:@selector(colletcClick:) forControlEvents:UIControlEventTouchUpInside];
    [_selectAddView.shareBtn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];


}

- (void)loadJiangYuanData
{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode=MBProgressHUDAnimationFade;//枚举类型不同的效果

    NSDictionary * dic = @{@"type":self.typeStr, @"opt":self.optStr, @"parentId":self.parentId, @"page":[NSString stringWithFormat:@"%ld", _pageNum], @"size":COUNT};
    [HttpTool postWithURL:kBasePostFuyin params:dic success:^(id json) {
        [self hiddenMBAction];
        if (_pageNum == 1) {
            [self.jiangYuanArr removeAllObjects];
        }
        JKSongsMessResult * results = [[JKSongsMessResult alloc] init];
        results.data = [json valueForKey:@"data"];
        NSArray * arr = [JKSongsMessStatus objectArrayWithKeyValuesArray:results.data];
        [self.jiangYuanArr addObjectsFromArray:arr];
        [self.jiangDaoTab reloadData];
        
        [_jiangDaoTab headerEndRefreshing];
        [_jiangDaoTab footerEndRefreshing];

    } failure:^(NSError *error) {
        [_jiangDaoTab headerEndRefreshing];
        [_jiangDaoTab footerEndRefreshing];
        [self hiddenMBAction];

    }];
    
}

- (void)leftBtnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)randomPlaySongs
{
    [TheHomeManager shareTheHomeManager].shengjPlayBool = 0;
    
    NSInteger tempIndex = random()%self.jiangYuanArr.count;
    JKSongsMessStatus * status = [self.jiangYuanArr objectAtIndex:tempIndex];
    
    PlayViewController * playVC = [[PlayViewController alloc] init];
    playVC.localPlayBool = NO;
    playVC.songIndex = tempIndex;
    playVC.songListArr = self.jiangYuanArr;
    playVC.listNameStr = status.album;
    playVC.playStyleNum = 1;
    
    playVC.imageUrl = [NSString stringWithFormat:@"%@", status.image];
    [playVC viewDidLoad];
    [playVC playMusicWithIndex:tempIndex];
    
    [self presentViewController:playVC animated:YES completion:nil];
    
    NSLog(@"随机播放全部");
}



#pragma mark - 下载,分享功能
- (void)downClick:(UIButton *)btn
{
    JKSongsMessStatus * status = [self.jiangYuanArr objectAtIndex:[[TheHomeManager shareTheHomeManager].selectIndex integerValue]];
    //单接口分享微信朋友圈
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate shareMusic:status type:1];
    NSLog(@"分享");
}
- (void)colletcClick:(UIButton *)btn
{
    JKSongsMessStatus * status = [self.jiangYuanArr objectAtIndex:[[TheHomeManager shareTheHomeManager].selectIndex integerValue]];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate shareMusic:status type:2];
    
    //单接口分享微信好友
    NSLog(@"分享");
}
- (void)shareClick:(UIButton *)btn
{
    JKSongsMessStatus * status = [self.jiangYuanArr objectAtIndex:[[TheHomeManager shareTheHomeManager].selectIndex integerValue]];
    NSString * imageStr = nil;
    if (status.image300.length > 0) {
        imageStr = status.image300;
    }else{
        imageStr = status.image;
    }
    [self willDownloadMusic:status.wma songName:status.MusicName singerName:status.singerName pic:imageStr pic300:imageStr pic1:imageStr zhuanjiName:status.album songTime:status.wma_time songID:status.songID nclassID:nil zhuanjiID:nil];
    
    
    NSLog(@"开始执行下载事件 第%@个", [TheHomeManager shareTheHomeManager].selectIndex);
    
    NSLog(@"下载");
}
- (void)willDownloadMusic:(NSString *)wmastr songName:(NSString *)nameStr singerName:(NSString *)singerName pic:(NSString *)pic pic300:(NSString *)pic300 pic1:(NSString *)pic1 zhuanjiName:(NSString *)zjName songTime:(NSString *)songTime songID:(NSString *)songID nclassID:(NSString *)nclassID zhuanjiID:(NSString *)zhaunjiID
{
    MBProgressHUD*hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode=MBProgressHUDModeText;//枚举类型不同的效果
    
    hud.labelText=@"下载已开始";
    [self performSelector:@selector(hiddenMBAction) withObject:nil afterDelay:0.5];
    
    [[FilesDownManage sharedFilesDownManage] downFileUrl:wmastr filename:nameStr singerName:singerName pic:pic pic300:nil pic1:nil zhuanjiName:zjName songTime:songTime songID:songID nclassID:nclassID zhuanjiID:zhaunjiID filetarget:@"mp3"];
    
    //    UINavigationController * myDownLoadNav = [[UINavigationController alloc] initWithRootViewController:[MyDownLoadViewController shareJKDownVC]];
    //    [self presentViewController:myDownLoadNav animated:YES completion:nil];
    
}
- (void)hiddenMBAction
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
#pragma mark - 讲道Tab
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    return self.jiangYuanArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JKSongsMessStatus * status = [self.jiangYuanArr objectAtIndex:indexPath.row];
    if ([[TheHomeManager shareTheHomeManager].selectID isEqualToString:status.songID]) {
        return 80;
    }
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    if (self.segmentMusicType.selectedSegmentIndex == 0) {      //热门讲道
    static NSString * cellStr = @"shigeCustomCell";
    ShiGeCustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (!cell) {
        cell = [[ShiGeCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
        cell.width = self.view.width;
        cell.height = 60;
    }

    cell.target = self;
    cell.action = @selector(cellDownLoadActionIndex:);
    cell.index = indexPath.row;
    JKSongsMessStatus * status = [self.jiangYuanArr objectAtIndex:indexPath.row];
    if ([[TheHomeManager shareTheHomeManager].selectID isEqualToString:status.songID]) {
        cell.height = 80;
    }else{
        cell.height = 60;
    }

    cell.status = status;
    cell.numLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row+1];
    if ([[TheHomeManager shareTheHomeManager].selectID isEqualToString:status.songID]) {
        [cell.allView addSubview:_selectAddView];
    }

    
//    cell.zjNameLabel.text = [NSString stringWithFormat:@"%@个专辑", status.total_album];
//    cell.downLoadView.hidden = YES;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [TheHomeManager shareTheHomeManager].shengjPlayBool = 0;
    
    JKSongsMessStatus * status = [self.jiangYuanArr objectAtIndex:indexPath.row];
    
    PlayViewController * playVC = [[PlayViewController alloc] init];
    playVC.localPlayBool = NO;
    playVC.songIndex = indexPath.row;
    playVC.songListArr = self.jiangYuanArr;
    playVC.listNameStr = status.album;
    
    [playVC viewDidLoad];
    [playVC playMusicWithIndex:indexPath.row];

}

#pragma mark - 更多功能
- (void)cellDownLoadActionIndex:(NSString *)index
{
    JKSongsMessStatus * statu = [self.jiangYuanArr objectAtIndex:[index integerValue]];
    NSLog(@"%@", statu.MusicName);
    if ([statu.songID isEqualToString:[TheHomeManager shareTheHomeManager].selectID]) {
        [TheHomeManager shareTheHomeManager].selectID = @"";
        [TheHomeManager shareTheHomeManager].selectIndex = @"";
    }else{
        [TheHomeManager shareTheHomeManager].selectID = statu.songID;
        [TheHomeManager shareTheHomeManager].selectIndex = index;
    }
    
    if ([TheHomeManager shareTheHomeManager].selectTab) {
        //        [[TheHomeManager shareTheHomeManager].selectTab reloadData];
    }
    
    [TheHomeManager shareTheHomeManager].selectTab = _jiangDaoTab;
    //    _indexSelect = indexPath.row;
    [_jiangDaoTab reloadData];
    
    return;
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - 懒加载
- (NSMutableArray *)jiangYuanArr
{
    if (_jiangYuanArr == nil) {
        self.jiangYuanArr = [NSMutableArray array];
    }
    return _jiangYuanArr;
}

@end
